import express from "express";
import * as articles from '../../controllers/articles.js';
import * as categories from '../../controllers/categories.js'
import * as comment from '../../controllers/comment.js'
import { count } from 'console';
import initUpload from '../../util/upload.js' 
const upload = initUpload()

const router = express.Router();

router.post("/publish",upload.single("cover"),async(req,res)=>{
    let title = req.body.title;
    let categoryId = req.body.categoryId;
    let content = req.body.content;
    let covers = req.body.cover;
    let data = await articles.insertArticle(title,covers,categoryId,content)
    res.send({
        code:200,
        msg:"ok了老铁",
        data:data
    })
})

router.get("/query",async(req,res)=>{
    let page = req.query.page;
      if(page==null || page==""){
        page = 1;
      }
      let perpage = req.query.perpage;
      if(perpage==null || perpage==""){
        perpage = 6;
      }
      let type = req.query.type;
      let key = req.query.key;
      let startIndex = (page-1)*perpage;
      let data = await articles.selectArticlesCondition(startIndex,perpage,type,key);
      res.send({
        code:200,
        msg:"查询成功",
        data:data
      })
})


router.get("/search",async(req,res)=>{
    let id = req.query?.id ?? "";
    
    let data = await articles.selectArticleSearch(id)
    res.send({
        code:200,
        msg:"查询成功",
        data:data
    })
})

router.post('/edit', upload.single(),async (req, res) => { 
    let id = req.body?.id ?? "";
   let title = req.body?.title ?? "";
   let cover = req.body?.cover;  
   let categoryId = req.body?.categoryId ?? "";  
   let date = req.body?.date ?? "";  
   let content = req.body?.content ?? "";
   let state = req.body?.state ?? "草稿";  
   
   if(id === "" || title === "" || categoryId === "" || date === "" || content === "") {
      return res.send({
         code: 400,
         msg: "修改失败"
      });
   }
   await articles.selectArticleEdit(title, cover, categoryId, date, content, state);
   res.send({
      code: 200,
      msg: "修改成功",
      
   });
});
export default router;